<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;

class PermissionResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'code' => $this->code,
            'type' => $this->type,
            'type_name' => $this->getTypeName(),
            'action' => $this->action,
            'action_name' => $this->getActionName(),
            'resource' => $this->resource,
            'menu_id' => $this->menu_id,
            'remark' => $this->remark,
            'menu' => $this->whenLoaded('menu', function () {
                return [
                    'id' => $this->menu->id,
                    'title' => $this->menu->title,
                ];
            }),
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
    }

    /**
     * 获取类型名称
     *
     * @return string
     */
    protected function getTypeName(): string
    {
        $types = \App\Models\Permission::getPermissionTypes();
        return $types[$this->type] ?? '未知';
    }

    /**
     * 获取操作名称
     *
     * @return string|null
     */
    protected function getActionName(): ?string
    {
        if (!$this->action) {
            return null;
        }
        
        $actions = \App\Models\Permission::getActionTypes();
        return $actions[$this->action] ?? $this->action;
    }
}

